
//
//  ClientManager.swift
//  Server
//
//  Created by 叶情宇 on 2017/7/4.
//  Copyright © 2017年 叶情宇. All rights reserved.
//

import Cocoa
import SwiftSocket
class ClientManager: NSObject {
    fileprivate var client : TCPClient
    fileprivate var isConnectToServer = false
    init(client:TCPClient) {
        self.client = client
    }
}

extension ClientManager{
    //1. 读取信息
    func readMessage() {
        isConnectToServer = true
        while isConnectToServer {
               //1.读取消息长度
            if let lengthMsg = client.read(4){
                let lengthData = Data(bytes: lengthMsg, count: 4)
                var length :Int = 0
                (lengthData as NSData).getBytes(&length, length: 4)
                print("消息长度\(length)")
                
                //2.读取消息类型
                guard let typeMsg = client.read(2)  else {
                    print("读取消息类型失败")
                    return
                }
                let typeData = Data(bytes: typeMsg, count: 2)
                var type:Int = 0
                (typeData as NSData).getBytes(&type, length: 2)
                print("消息类型\(type)")
                //3.读取真实消息的内容
                guard let msgbyte =  client.read(length) else {
                    print("读取消息失败")
                    return
                }
                let data = Data(bytes: msgbyte, count: length)
                let mss =  String.init(data: data, encoding: .utf8)
                print(mss ?? "KO")
                let userInfo = try? GiftMessage.parseFrom(data: data)
                print("用户名\((userInfo?.giftUrl) ?? "空")")
    
            }else{
             isConnectToServer = false
             print("客户端断开连接")
             client.close()
            }
        }
    }
}
